package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsPurchaseOrderDetailedMapper;
import com.jy.wms.dao.WmsPurchaseOrderMapper;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: WmsPurchaseOrderService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author lh
 * @Date Fri Sep 15 17:36:51 GMT+08:00 2017
 */

@Service
public class WmsPurchaseOrderService extends BaseService<WmsPurchaseOrderMapper, WmsPurchaseOrder> {

    @Autowired
    private WmsPurchaseOrderDetailedMapper wmsPurchaseOrderDetailedMapper;
    @Autowired
    private WmsSplitService wmsSplitService;
    /**
     * 通过货主id查询对应的所有供应商
     *
     * @param hzid
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "通过货主id查询对应的所有供应商")
    public List<WmsOwnerSupplier> getWosByHzid(String hzid, String ckid) throws ServiceException {

        try {
            return dao.getWosByHzid(hzid, ckid);
        } catch (Exception e) {
            throw new ServiceException("通过货主id查询对应的所有供应商", e);
        }
    }

    //xxx改动
    @BaseServiceDescribe(moduleName = "采购订单管理01", btnName = "通过货主id查询对应的所有供应商01")
    public List<WmsOwnerSupplier> getWosByHzidInfo(String hzid, String ckid,Map map) throws ServiceException {

        try {
            return dao.getWosByHzidInfo(hzid, ckid,map);
        } catch (Exception e) {
            throw new ServiceException("通过货主id查询对应的所有供应商", e);
        }
    }
    /**
     * 获取订单（PO）类型
     *
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "获取订单（PO）类型")
    public List<WmsOwnerOrdertype> getPoLx(String hzid, String ckid, String ddlx) throws ServiceException {
        try {
            return dao.getPoLx(hzid, ckid, ddlx);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取订单（PO）类型", e);
        }
    }

    /**
     * 查询当前货主下的货品
     *
     * @param gysid 供应商id
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "查询当前货主下的货品")
    public List<WmsPurchaseOrder> getGoods(String gysid, String ckid, String goodsBh) throws ServiceException {
        try {
            return dao.getGoods(gysid, ckid, goodsBh);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询当前货主下的货品", e);
        }
    }

    /**
     * 查询货品包装所对应的包装明细
     *
     * @param bzid
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "查询货品包装所对应的包装明细")
    public List<WmsPackingDetailed> packDetailList(String bzid, String ckid) throws ServiceException {
        try {
            List<WmsPackingDetailed> list = dao.packDetailList(bzid, ckid);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询货品包装所对应的包装明细", e);
        }
    }

    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     * @return int
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "增加订单")

    @Transactional(rollbackFor = RuntimeException.class)

    public Integer baseInsert(WmsPurchaseOrder entity, String lx) throws SucessException, ServiceException {
        if (CommonInfo.zdsh.getType().equals(entity.getZdsh())) {
            entity.setDdshr("超级管理员");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date d = new Date();
        String date = df.format(d);// new Date()为获取当前系统时间
        entity.setCjsj(date);
        entity.setXgsj(date);
        entity.setYjdhsj(df.format(new Date(Long.valueOf(entity.getYjdhsj()).longValue())));
        List<WmsPurchaseOrderDetailed> lists = entity.getWpodList();//明细集合
        for (int i = 0; i < lists.size() - 1; i++) {
            for (int j = i + 1; j < lists.size(); j++) {
                if (lists.get(j).getHpid().equals(lists.get(i).getHpid())) {
                    throw new ServiceException("订单明细包含重复货品,添加失败");
                }
            }
        }
        Integer e = dao.getCountByBh(entity.getHzid(), entity.getBh());//查询订单编号是否重复(同一货主不可重复)
        if (e <= 0) {//判断订单编号是否重复
            Integer a = dao.baseInsertSelective(entity);//保存采购订单
            Integer b = 0;
            if (a > 0) {
                for (WmsPurchaseOrderDetailed wpod : lists) {
                        wpod.setSscgdid(entity.getId());
                        wpod.setCkid(entity.getCkid());
                        wpod.setId(UUIDUtils.uuid());
                        wpod.setCjsj(date);
                        b = wmsPurchaseOrderDetailedMapper.baseInsert(wpod);//增加订单明细
                }

                if (b > 0) {
                    throw new SucessException("采购订单添加成功");
                } else {
                    //如果明细添加失败那么回去删掉采购订单
                    Integer c = dao.deleteOrder(entity.getId());
                    throw new ServiceException("采购订单添加失败");
                }
            } else {
                throw new ServiceException("采购订单添加失败");
            }
        } else {
            throw new ServiceException("采购订单编号重复,添加失败");
        }
    }

    /**
     * 删除（根据ID 批量删除）
     *
     * @param idList 主键ID列表
     * @return int
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "删除采购订单")
    @Transactional
    public Integer baseDeleteBathPrimaryKeys(List<String> idList, String scr) throws SucessException, ServiceException {

        //获取选中id的集合
        List<WmsPurchaseOrder> list = dao.getOrderList(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsPurchaseOrder wpo : list) {
            //未审核
            if (CommonInfo.purchaseOrder_wsh.getType().equals(wpo.getShzt())) {
                list2.add(wpo.getId());
            }
        }
        if (list2.size() > 0) {
            Integer a = wmsPurchaseOrderDetailedMapper.baseDeleteBathPrimaryKeys(list2);//将采购订单所对应的明细的状态更改为3取消订单
            Integer b = dao.baseDeleteBathPrimaryKeys(list2, scr);//删除采购订单（将订单状态更改为3取消订单）
            if (b > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，删除成功" + b + "条记录");
            } else {
                throw new ServiceException("采购订单删除失败");
            }
        } else {
            throw new ServiceException("选中的记录已经全部审核，不可以删除");
        }

    }

    public Integer deleteByIdss(String id) {
        return dao.deleteOrder(id);
    }

    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsPurchaseOrder>
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "分页查询")
    public Page<WmsPurchaseOrder> baseSelectPage(WmsPurchaseOrder entity, String hzid, String gysid, String ckid) {

      /*  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//时间转换成毫秒

        if (entity.getCjsj_start() != null && entity.getCjsj_start() != "") {
            entity.setCjsj_start(format.format(new Date(Long.parseLong(entity.getCjsj_start()))));
        }
        if (entity.getCjsj_end() != null && entity.getCjsj_end() != "") {
            entity.setCjsj_end(format.format(new Date(Long.parseLong(entity.getCjsj_end()))));
        }*/
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsPurchaseOrder>) dao.baseSelectPage(entity, hzid, gysid, ckid);
    }

    /**
     * 查询（根据主键ID查询）
     *
     * @param id 采购订单id
     * @return WmsPurchaseOrder
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "查询采购订单及明细")
    public JSONObject baseSelectByPrimaryKey(String id) throws ServiceException {
        try {
            JSONObject jb = new JSONObject();
            WmsPurchaseOrder wpo = dao.baseSelectByPrimaryKey(id);//采购订单
            JSONObject wmsPurchaseOrder = JSONObject.fromObject(wpo);
            List<WmsPurchaseOrderDetailed> list = dao.wmsPurchaseOrderDetailList(id);//采购订单明细
            JSONArray wmsPurchaseOrderDetailed = JSONArray.fromObject(list);
            jb.put("WmsPurchaseOrder", wmsPurchaseOrder);
            jb.put("wmsPurchaseOrderDetailed", wmsPurchaseOrderDetailed);
            return jb;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询采购订单及明细", e);
        }
    }


    /**
     * 修改 （匹配有值的字段）
     *
     * @param entity 采购订单实体
     * @return int
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "修改采购订单")
    public Integer baseUpdateByPrimaryKeySelective(WmsPurchaseOrder entity) throws SucessException, ServiceException {
        if (CommonInfo.zdsh.getType().equals(entity.getZdsh())) {//自动审核
            entity.setDdshr("超级管理员");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date d = new Date();
        String date = df.format(d);// new Date()为获取当前系统时间
        entity.setCjsj(date);
        entity.setYjdhsj(df.format(new Date(Long.valueOf(entity.getYjdhsj()).longValue())));
        WmsPurchaseOrder wmsPurchaseOrder = dao.baseSelectByPrimaryKey(entity.getId());//通过id查询对象
        if (wmsPurchaseOrder.getShzt().equals(CommonInfo.purchaseOrder_ysh.getType())) {
            throw new ServiceException("订单已审核，不可以进行编辑");
        } else {
            Integer e = 0;
            if (wmsPurchaseOrder.getBh().equals(entity.getBh())) {
                //如果修改之后的编号和之前的编号相同，那么直接给编号空值，sql里不给予修改，若不相同那么查询编号是否重复
                entity.setBh("");
            } else {
                e = dao.getCountByBh(entity.getHzid(), entity.getBh());//查询订单编号是否重复(同一货主不可重复)
            }
            if (e <= 0) {
                Integer a = dao.baseUpdateByPrimaryKeySelective(entity);//修改采购订单
                if (a > 0) {
                    throw new SucessException("采购订单修改成功");
                } else {
                    throw new ServiceException("采购订单修改失败");
                }
            } else {
                throw new ServiceException("订单编号重复，添加失败");
            }
        }
    }

    /**
     * 修改订单明细 （匹配有值的字段）
     *
     * @param entity 主键ID列表
     * @return int
     */
   /* @BaseServiceDescribe(moduleName = "采购订单", btnName = "修改采购订单明细")
    public Integer baseUpdateMx(WmsPurchaseOrderDetailed entity) throws SucessException, ServiceException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date d = new Date();
        String date = df.format(d);// new Date()为获取当前系统时间
        WmsPurchaseOrder wmsPurchaseOrder = dao.baseSelectByPrimaryKey(entity.getSscgdid());//通过采购订单id查询对象
        if (wmsPurchaseOrder.getShzt().equals("1")) {
            throw new ServiceException("订单已审核，不可以进行编辑");
        } else {
            //如果id 为空，那么需要新加一条数据进数据库明细表，否则修改原来的明细
            if (entity.getId() == null || entity.getId().equals("") || entity.getId() == "") {
                entity.setId(UUIDUtils.uuid());
                entity.setCjsj(date);
                //查询当前采购订单下是否有相同的货品
                Integer a = dao.getMxCountByDdid(entity.getSscgdid(), entity.getHpid(), "");
                if (a > 0) {
                    throw new ServiceException("当前采购订单下包含重复货品，修改失败");
                } else {
                    //增加明细
                    Integer b = wmsPurchaseOrderDetailedMapper.baseInsertSelective(entity);
                    if (b > 0) {
                        throw new SucessException("订单明细增加成功");
                    } else {
                        throw new ServiceException("订单明细增加失败");
                    }
                }
            } else {
                //查询当前采购订单下是否有相同的货品(如果货品更改了，那么要在数据库查找是否有相同的货品
                // （查询的时候排除当前修改的这条明细，因为当前明细要被更改））)
                Integer a = dao.getMxCountByDdid(entity.getSscgdid(), entity.getHpid(), entity.getId());
                if (a > 0) {
                    throw new ServiceException("当前采购订单下包含重复货品，修改失败");
                } else {
                    //修改明细
                    Integer b = wmsPurchaseOrderDetailedMapper.baseUpdateByPrimaryKey(entity);
                    if (b > 0) {
                        throw new SucessException("订单明细修改成功");
                    } else {
                        throw new ServiceException("订单明细修改失败");
                    }
                }
            }
        }
    }
*/

    /**
     * 查找仓库
     *
     * @param id 仓库id
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "查找仓库")
    public WmsWarehouse getWmsWarehouse(String id) {
        return dao.getWmsWarehouse(id);
    }

    /**
     * 审核通过之后修改审核状态
     *
     * @param idList 采购订单id 集合
     * @param shr  审核人
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "审核采购订单")
    public void updateShzt(List<String> idList, String shr, UserInfo userinfo) throws SucessException, ServiceException,Exception {
        //获取选中id的集合
        List<WmsPurchaseOrder> list = dao.getOrderList(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsPurchaseOrder wpo : list) {
            //未审核
            if (CommonInfo.purchaseOrder_wsh.getType().equals(wpo.getShzt())) {
                list2.add(wpo.getId());
            }
        }
        if (list2.size() > 0) {
            Integer a = dao.updateShzt(list2, shr);
            SetAndModifyModel setAndModifyModel = new SetAndModifyModel();
            setAndModifyModel.setIds(list2);
            //wmsSplitService.split(setAndModifyModel,userinfo.getUser().getName(),String.valueOf(userinfo.getUser().getOrgId().get(0)));
            if (a > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，审核成功" + a + "条记录");
            } else {
                throw new ServiceException("采购订单审核失败");
            }
        } else {
            throw new ServiceException("选中的记录已经全部审核，不可以再次审核");
        }
    }

    /**
     *
     * @param idList 采购订单id集合
     * @param czr 操作人
     * @return
     */
    @Transactional
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "标记采购订单收货完成")
    public Integer updateZt(List<String> idList, String czr) throws SucessException, ServiceException {
        //获取选中id的集合
        List<WmsPurchaseOrder> list = dao.getOrderList(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsPurchaseOrder wpo : list) {
            //1、部分收货(对部分收货的采购订单手动完结订单,标记此订单不再收货。
            // 标记完成后将PO状态改为“订单完成”,订单行状态为“部分收货”或“初始”的订单行将行状态改为“订单完成”。)
            if (CommonInfo.purchaseOrder_zt_bfsh.getType().equals(wpo.getZt())) {
                list2.add(wpo.getId());
            }
        }
        if (list2.size() > 0) {
            Integer a = dao.updateZt(list2, czr);
            //修改订单明细的状态
            Integer b = dao.updateMxZt(list2);
            if (a > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，标记成功" + a + "条记录");
            } else {
                throw new ServiceException("标记收货完成失败");
            }
        } else {
            throw new ServiceException("选中的记录不包含部分收货状态的订单，不可以进行标记");
        }
    }

    /**
     * 导出采购订单
     *
     * @param ids
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "导出采购订单")
    public List<WmsPurchaseOrder> getOutPutList(List<String> ids,/*WmsPurchaseOrder wpo,*/Map map) {
//        String bh=map.get("bh");
//        String lx=map.get("lx");
//        String zt=map.get("zt");
//        String shzt=map.get("shzt");
//        String cjsj_start=map.get("cjsj_start");
//        String cjsj_end=map.get("cjsj_end");
//        String gysid=map.get("gysid");
        List<WmsPurchaseOrder> list = dao.getOutPutList(ids, map);
        return list;

    }

    /**
     * 供应商id 查询供应商
     */
    @BaseServiceDescribe(moduleName = "采购订单", btnName = "根据id查询供应商")

    public WmsOwnerSupplier getSupplier(@Param("gysid") String gysid, @Param("ckid") String ckid) {
        return dao.getSupplier(gysid, ckid);
    }
    //getSupplierInfo
    public WmsOwnerSupplier getSupplierInfo(@Param("gysid") String gysid, @Param("ckid") String ckid,@Param("Map") Map map) {
        return dao.getSupplierInfo(gysid,ckid,map);
    }
    /**
     * 通过供应商编号获取供应商
     *
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "通过供应商编号获取供应商")
    public WmsOwnerSupplier getSupplierByGysid(String gysid, String ckid) throws ServiceException {
        try {
            return dao.getSupplierByGysid(gysid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取供应商", e);
        }
    }


    /**
     * 通过货品编号获取货品
     *
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "通过货品编号获取货品")
    public WmsPurchaseOrder getGoodsByHpid(String hpid, String ckid) throws ServiceException {
        try {
            return dao.getGoodsByHpid(hpid, ckid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取货品", e);
        }
    }


    /**
     * 通过货品编号获取货品
     *
     * @return
     */
    @BaseServiceDescribe(moduleName = "采购订单管理", btnName = "根据采购订单id 查询订单明细")
    public List<WmsPurchaseOrderDetailed> wmsPurchaseOrderDetailList(String sscgdid) throws ServiceException {
        try {
            return dao.wmsPurchaseOrderDetailList(sscgdid);//采购订单明细
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取货品", e);
        }
    }

    /**
     * 根据采购订单id 查询预期到货通知单
     * @param ccddid 采购订单id
     * @param ckid 仓库id
     * @return 预期到货通知单集合
     */
    public Page<WmsEstimatedArrivalOrder>  getWmsEstimatedArrivalOrders(String ccddid, String ckid, int page, int rows){
        PageHelper.startPage(page, rows);
        return (Page<WmsEstimatedArrivalOrder>) dao.getWmsEstimatedArrivalOrders(ccddid,ckid);
    }
}
